﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;

namespace ASBCC.MailService
{
    partial class MailService : ServiceBase
    {
        private System.Timers.Timer ServiceTimer = new System.Timers.Timer();
        private string connstr;
        private NetMailUtility nmu;

        public MailService()
        {
            InitializeComponent();
            ServiceTimer.Interval = Config.IntervalMinutes * 60 * 1000;
            ServiceTimer.Enabled = true;
            ServiceTimer.Elapsed += new System.Timers.ElapsedEventHandler(ServiceTimer_Elapsed);
        }

        private void ServiceTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            System.Diagnostics.EventLog.WriteEntry("EZVisit Send Mail Service Start",
                "Send mail service started at " + System.DateTime.Now.ToString(), System.Diagnostics.EventLogEntryType.Information, 0);

            ServiceTimer.Enabled = false;
            try
            {
                nmu.SendMails();
            }
            catch (Exception ee)
            {
                System.Diagnostics.EventLog.WriteEntry("EZVisit Send Mail Service throw Exception!",
                "Send mail service throwed exception at " + System.DateTime.Now.ToString() + ":" + ee.Message, System.Diagnostics.EventLogEntryType.Error, 0);

            }
            ServiceTimer.Enabled = true;

            System.Diagnostics.EventLog.WriteEntry("EZVisit Send Mail Service End",
                   "Send mail service ended at " + System.DateTime.Now.ToString(), System.Diagnostics.EventLogEntryType.Information, 0);

        }

        public void Run()
        {
            OnStart(null);
        }

        protected override void OnStart(string[] args)
        {
            connstr = Config.ConnectionString;
            if (Config.EncryptConnectionString)
            {
                connstr = Security.Decrypt(connstr);
            }
            nmu = new NetMailUtility(connstr,
                Config.Host,
                Config.UserName,
                Config.Password,
                Config.MailAmount,
                Config.LiveMode,
                Config.TestModeRecipients,
                Config.Sender,
                Config.SenderDisplayName,
                Config.EnableSsl,
                Config.LogFile,
                Config.SaveSucceedLog,
                Config.SaveFailedLog);
        }

        protected override void OnStop()
        {
            // TODO: Add code here to perform any tear-down necessary to stop your service.
        }
    }
}
